<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j page-submit-order">
    <div class="content">
      <div class="step-box">
        <div class="left">
          <span class="img" />
          <span class="text">{{ $t('submitOrder.submitOrder') }}</span>
        </div>
        <div class="steps">
          <div class="item">
            <div class="number">
              step 01.
            </div>
            <div class="text">
              {{ $t('submitOrder.selectProductToBuy') }}
            </div>
          </div>
          <div class="item active">
            <div class="number">
              step 02.
            </div>
            <div class="text">
              {{ $t('submitOrder.confirmOrderInformation') }}
            </div>
          </div>
          <div class="item">
            <div class="number">
              step 03.
            </div>
            <div class="text">
              {{ $t('submitOrder.payToCompleteTheOrder') }}
            </div>
          </div>
        </div>
      </div>
      <div class="submit-con">
        <!-- 收货地址 (mold=1虚拟商品不展示收货地址) -->
        <div
          v-if="mold !== 1"
          class="submit-box submit-box-border"
        >
          <div class="tit">
            <span class="text">{{ $t('address.receivingAddress') }}</span>
            <!-- <span class="action">显示全部地址</span> -->
          </div>
          <div class="con address-box">
            <div
              v-for="address in addressList"
              :key="address.addrId"
              :class="[
                'item',
                address.commonAddr ? 'default-address' : '',
                selectedAddrId === address.addrId ? 'active' : ''
              ]"
              @click="changeAddress(address.addrId)"
            >
              <div class="name-phone">
                <span class="name">{{ address.receiver }}</span>
                <span class="phone">{{ address.mobile }}</span>
                <span
                  v-if="!address.commonAddr"
                  class="set-default"
                  @click="setDefaultAddr(address.addrId)"
                >{{ $t('address.setDefault') }}</span>
                <span
                  v-if="address.commonAddr"
                  class="default-tag"
                >{{ $t('address.default') }}</span>
              </div>
              <div class="address-detail">
                {{
                  address.province + address.city + address.area + address.addr
                }}
              </div>
              <div class="del-edit">
                <span
                  class="edit"
                  @click.stop="editAddr(address.addrId)"
                />
                <span
                  class="del"
                  @click.stop="toggleDelAddr(true, address.addrId)"
                />
              </div>
            </div>
            <div
              v-if="addressList.length<10"
              class="item add-address"
              @click="toggleAddrPop(true)"
            >
              <div class="add-box">
                <div class="img">
                  +
                </div>
                <div class="text">
                  {{ $t('address.addAddress') }}
                </div>
              </div>
            </div>
          </div>
          <div
            v-if="showDelAddr"
            class="popup-mask"
          />
          <div class="fix-transform-blur">
            <div
              v-if="showDelAddr"
              class="popup-box"
            >
              <div
                class="tit"
                style="padding:10px;"
              >
                <div class="text">
                  {{ $t('tips') }}
                </div>
                <div
                  class="close"
                  @click="toggleDelAddr(false)"
                />
              </div>
              <div class="con">
                <div class="tip">
                  <div class="tip-icon warning" />
                  <div class="tip-info">
                    <div class="result">
                      {{ $t('address.deleteShippingAddress') }}
                    </div>
                    <div class="date">
                      {{ $t('address.deleteShippingTips') }}
                    </div>
                    <div class="btns">
                      <a
                        href="javascript:void(0);"
                        class="btn-r"
                        @click="delAddr()"
                      >{{ $t('delete') }}</a>
                      <a
                        href="javascript:void(0);"
                        class="btn-g"
                        @click="toggleDelAddr(flase)"
                      >{{ $t('cancel') }}</a>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 收货地址 -->
        <!-- 支付方式 -->
        <div class="submit-box submit-box-border">
          <div class="tit">
            <span class="text">{{ $t('commonFoot.paymentMethod') }}</span>
          </div>
          <div class="con pay-way">
            <div class="item active">
              {{ $t('submitOrder.payOnline') }}
            </div>
          </div>
        </div>
        <!-- 支付方式 -->
        <!-- 积分抵扣 -->
        <div
          v-if="orderInfo.maxUsableScore > 0"
          class="submit-box integral-box submit-box-border"
        >
          <div class="tit">
            <span class="text">{{ $t('submitOrder.pointsCredit') }}</span>
          </div>
          <!-- 积分抵现 -->
          <div class="integral-item pointsCredit-integral-item">
            <label
              class="text checkbox-text"
            >
              <el-checkbox
                v-model="checked"
                :disabled="isProhibit"
                class="item-group"
                @change="useMemberPoints"
              />{{ $t('submitOrder.usePointsForCrediting') }}
            </label>
            <div class="con" />
          </div>
          <!-- 积分抵现 -->
          <div
            v-if="isScorePay === 1"
            class="integral-item integral-input-box"
          >
            {{ $t('submitOrder.accountTotal') }} {{ accountCanUseScore }}{{ $t('submitOrder.pointThisUse') }}
            <input
              v-model="userUseScore"
              type="number"
              class="text"
              @input="inputComplete()"
            >
            {{ $t('submitOrder.pcsCredit') }}
            <span class="integral-money">
              ￥{{
                userUseScore
                  ? Number(orderInfo.totalScoreAmount).toFixed(2)
                  : '0.00'
              }}
            </span>
            <span>
              （{{ $t('submitOrder.theOrderIsAvailableUpTo') }} {{ orderInfo.maxUsableScore }} {{ $t('submitOrder.points') }}）
              <span v-if="shopUseScore > 100">{{ ($t('submitOrder.pleaseEnterAMultipleOf10')) }}</span>
            </span>
          </div>
          <div
            v-if="isScorePay === 1"
            class="integral-item integral-text"
          >
            <span class="font-bold">
              {{ $t('submitOrder.amountCredit') }}
              <span class="integral-money">
                ￥{{
                  userUseScore
                    ? Number(orderInfo.totalScoreAmount).toFixed(2)
                    : '0.00'
                }}
              </span>
            </span>
            <span class="text-item font-bright">
              {{ $t('submitOrder.use') }}￥
              {{
                userUseScore
                  ? Number(orderInfo.totalScoreAmount).toFixed(2)
                  : '0.00'
              }}
            </span>
          </div>
        </div>
        <!-- 积分抵扣 -->

        <!-- 全部留言（虚拟商品）/ -->
        <!-- 配送方式 -->
        <div
          v-if="mold !== 1"
          class="submit-box submit-box-border"
        >
          <div class="tit">
            <span class="text">{{ $t('submitOrder.deliveryMethod') }}</span>
          </div>
          <div class="con delivery-way">
            <div class="item active">
              {{ $t('submitOrder.courierDelivery') }}
            </div>
            <!-- <div class="item">到店自提</div> -->
            <!-- <div class="description">（该商品不支持自提）</div> -->
          </div>
        </div>
        <!-- /配送方式 -->
        <!-- 商品信息 -->
        <div
          class="submit-box goods-info"
          :class="{'last-box': !(platformCoupons && platformCoupons.canUseCoupons.length > 0) }"
        >
          <div class="tit">
            <span class="text">{{ $t('applyReturn.productInformation') }}</span>
          </div>
          <div class="goods-msg">
            <div class="msg-tab">
              <div class="img">
&nbsp;
              </div>
              <div class="info">
                {{ $t('products') }}
              </div>
              <div class="unit-price">
                {{ $t('priceOne') }}
              </div>
              <div class="number">
                {{ $t('quantity') }}
              </div>
              <div class="total">
                {{ $t('subtotal') }}
              </div>
            </div>
            <div
              v-for="(shopCart, shopIndex) in shopCartOrders"
              :key="shopCart.shopId"
              class="msg-con"
              :class="{'last-box': (platformCoupons && platformCoupons.canUseCoupons.length > 0) }"
            >
              <!-- 店铺 -->
              <div class="shop-msg">
                <span class="shop-name">{{ $t('index.shop') }}：</span>
                <router-link
                  :to="{
                    path: '/shop-index',
                    query: {
                      sid: shopCart.shopId
                    }
                  }"
                  class="shop-name"
                >
                  {{ shopCart.shopName }}
                </router-link>
                <span
                  v-if="shopCart.shopId === 1"
                  class="self"
                >{{ $t('prodDetail.selfEmployed') }}</span>
              </div>
              <!-- 店铺中的商品 -->
              <div
                v-for="(shopCartItemDiscount,
                        discIndex) in shopCart.shopCartItemDiscounts"
                :key="discIndex"
                class
              >
                <div
                  v-for="(prod,
                          prodIndex) in shopCartItemDiscount.shopCartItems"
                  :key="prodIndex"
                  class="goods-box"
                >
                  <div class="prod-row">
                    <div class="img">
                      <router-link
                        :to="{
                          path:'/detail',
                          query:{
                            prodId:prod.prodId
                          }
                        }"
                        class="img-box"
                        target="_blank"
                      >
                        <img-show :src="prod.pic" />
                      </router-link>
                      <div
                        v-if="!(prod.isDelivery)"
                        class="no-delivery"
                      >
                        不支持配送
                      </div>
                    </div>
                    <div class="info">
                      <router-link
                        :to="{
                          path:'/detail',
                          query:{
                            prodId:prod.prodId
                          }
                        }"
                        class="name"
                        target="_blank"
                      >
                        {{
                          prod.prodName
                        }}
                      </router-link>
                      <span class="sku">{{ prod.skuName }}</span>
                      <span
                        v-if="prod.preSellTime"
                        class="sku"
                      >{{ formatDate(prod.preSellTime) }}&nbsp;{{ $t('prodDetail.startShipping') }}</span>
                    </div>
                    <div class="unit-price">
                      ￥{{ parsePrice(prod.price)[0] }}.{{
                        parsePrice(prod.price)[1]
                      }}
                    </div>
                    <div class="number">
                      ×{{ prod.prodCount }}
                    </div>
                    <div
                      v-if="!(prod.isDelivery)"
                      class="total"
                    >
                      ￥0.00
                    </div>
                    <div
                      v-else
                      class="total"
                    >
                      ￥{{ parsePrice(prod.productTotalAmount)[0] }}.{{
                        parsePrice(prod.productTotalAmount)[1]
                      }}
                    </div>
                  </div>
                  <!-- 赠品展示 -->
                  <div
                    v-if="prod.giveaway"
                    class="gift-con"
                  >
                    <div
                      v-for="(giveawayItem, giveawayIndex) in prod.giveaway.giveawayProds"
                      :key="giveawayIndex"
                      class="gift-item"
                    >
                      <router-link
                        class="gift-item-name"
                        :to="{
                          path:'/detail',
                          query:{
                            prodId:giveawayItem.prodId
                          }
                        }"
                        target="_blank"
                      >
                        {{ $t('cart.giveaways') }} {{ giveawayItem.prodName }}
                        <span class="gift-item-sku-name">{{ giveawayItem.skuName }} x{{ giveawayItem.giveawayNum }}</span>
                      </router-link>
                    </div>
                  </div>
                  <!-- 虚拟商品留言 start -->
                  <div
                    v-if="prod.virtualRemarkList && prod.virtualRemarkList.length"
                    class="virtual-goods-msg"
                  >
                    <div :class="['msg-tit',$t('language')==='en' ? 'msg-tit-en' : '']">
                      <span class="text">{{ $t('submitOrder.userMessage') }}：</span>
                    </div>
                    <div>
                      <div
                        v-for="(msgItem,msgIndex) in prod.virtualRemarkList"
                        :key="msgIndex"
                        class="msg-item"
                      >
                        <span
                          v-if="msgItem.isRequired"
                          class="red-stress"
                        >*</span>
                        <input
                          v-model="msgItem.value"
                          class="msg-int-item"
                          type="text"
                          :placeholder="$t('submitOrder.pleaseEnter') + `${msgItem.name}`"
                          maxlength="20"
                          @blur="handleInputBlur(msgItem.value, msgIndex, prodIndex, discIndex, shopIndex)"
                        >
                      </div>
                    </div>
                  </div>
                  <!-- 虚拟商品留言 end -->
                </div>
              </div>

              <!-- 留言 -->
              <div class="remake-box">
                {{ $t('orderDetails.orderRemarks') }}：
                <input
                  v-model="shopCart.remarks"
                  type="text"
                  class="text"
                  maxlength="100"
                  :data-shopinde="shopIndex"
                  :data-shopitem="shopCart"
                  :placeholder="$t('submitOrder.numberLength100')"
                >
                <!-- 发票 -->
                <template v-if="shopCart.actualTotal">
                  <div class="invoice-title">
                    {{ $t('invoice.invoiceInfo') }}
                  </div>
                  <div
                    v-if="shopCart.invoiceDataFrom"
                    class="invoice-box"
                  >
                    <div
                      v-if="shopCart.invoiceDataFrom.invoiceType === 1"
                      class="invoice-box-item invoice-type"
                    >
                      {{ $t('invoice.generalInvoice') }}
                    </div>
                    <div
                      v-if="shopCart.invoiceDataFrom.invoiceType === 2 || !shopCart.invoiceDataFrom"
                      class="invoice-box-item invoice-type"
                    >
                      {{ $t('invoice.noInvoice') }}
                    </div>
                    <div
                      v-if="shopCart.invoiceDataFrom.invoiceType === 1"
                      class="invoice-box-item invoice-unit"
                    >
                      {{ shopCart.invoiceDataFrom.headerName || $t('invoice.personal') }}
                    </div>
                    <div
                      v-if="shopCart.invoiceDataFrom.invoiceType === 1"
                      class="invoice-box-item invoice-contents"
                    >
                      {{ $t('invoice.productDetails') }}
                    </div>
                    <div
                      class="invoice-box-item invoice-operation"
                      @click="showAddOrUpdateDialog(0,shopCart,shopCart.shopId)"
                    >
                      {{ $t('invoice.update') }}
                    </div>
                  </div>
                  <div
                    v-else
                    class="invoice-box"
                  >
                    <div class="invoice-box-item invoice-type">
                      {{ $t('invoice.noInvoice') }}
                    </div>
                    <div
                      class="invoice-box-item invoice-operation"
                      @click="showAddOrUpdateDialog(0,shopCart,shopCart.shopId)"
                    >
                      {{ $t('invoice.update') }}
                    </div>
                  </div>
                </template>
                <!-- 发票 -->
              </div>
              <!-- /留言 -->

              <!-- 优惠券选择框 -->
              <coupon-select
                v-if="
                  shopCart.shopCoupons &&
                    (shopCart.shopCoupons.canUseCoupons.length > 0 || shopCart.shopCoupons.unCanUseCoupons.length > 0)
                "
                :coupons="shopCart.shopCoupons"
                @check-coupon="checkCoupon"
              />
              <!-- 优惠券选择框 -->
            </div>

            <!-- 不支持配送商品 -->
            <div
              v-for="(shopCart, shopIndex) in filterShopItems"
              :key="shopIndex"
              class="msg-con"
            >
              <!-- 店铺 -->
              <div class="shop-msg">
                <span class="shop-name">{{ $t('index.shop') }}：</span>
                <router-link
                  :to="{
                    path: '/shop-index',
                    query: {
                      sid: shopCart.shopId
                    }
                  }"
                  class="shop-name"
                >
                  {{ shopCart.shopName }}
                </router-link>
                <span
                  v-if="shopCart.shopId === 1"
                  class="self"
                >{{ $t('prodDetail.selfEmployed') }}</span>
              </div>
              <!-- 店铺中的商品 -->
              <div
                v-for="(prod,
                        prodIndex) in shopCart.shopCartItems"
                :key="prodIndex"
              >
                <div
                  class="goods-box"
                >
                  <div class="prod-row">
                    <div class="img">
                      <router-link
                        :to="{
                          path:'/detail',
                          query:{
                            prodId:prod.prodId
                          }
                        }"
                        class="img-box"
                        target="_blank"
                      >
                        <img-show :src="prod.pic" />
                      </router-link>
                      <div class="no-delivery">
                        不支持配送
                      </div>
                    </div>
                    <div class="info">
                      <router-link
                        :to="{
                          path:'/detail',
                          query:{
                            prodId:prod.prodId
                          }
                        }"
                        class="name"
                        target="_blank"
                      >
                        {{
                          prod.prodName
                        }}
                      </router-link>
                      <span class="sku">{{ prod.skuName }}</span>
                      <span
                        v-if="prod.preSellTime"
                        class="sku"
                      >{{ formatDate(prod.preSellTime) }}&nbsp;{{ $t('prodDetail.startShipping') }}</span>
                    </div>
                    <div class="unit-price">
                      ￥{{ parsePrice(prod.price)[0] }}.{{
                        parsePrice(prod.price)[1]
                      }}
                    </div>
                    <div class="number">
                      ×{{ prod.prodCount }}
                    </div>
                    <div class="total">
                      ￥0.00
                    </div>
                  </div>
                  <!-- 虚拟商品留言 end -->
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 商品信息 -->
        <!-- 发票信息 -->
        <!-- <div class="submit-box">
          <div class="tit">
            <span class="text">发票信息</span>
          </div>
          <div class="con invoice-msg">
            <div class="invoice-text">电子普通发票</div>
            <div class="invoice-text">个人</div>
            <div class="invoice-text">商品明细</div>
            <a href=""
               class="invoice-btn">修改</a>
          </div>
        </div>-->
        <!-- /发票信息 -->
        <!-- 优惠券选择框 -->
        <div
          v-if="platformCoupons && (platformCoupons.unCanUseCoupons.length > 0 || platformCoupons.canUseCoupons.length > 0)"
          class="submit-box submit-box-border"
        >
          <div class="tit">
            <span class="text">{{ $t('submitOrder.platformCoupons') }}</span>
          </div>
          <coupon-select
            :coupons="platformCoupons"
            :platform="true"
            @check-coupon="checkCoupon"
          />
        </div>
      </div>

      <!-- 金额明细 -->
      <div class="submit-bottom">
        <!-- 优惠明细 -->
        <div
          v-if="orderInfo.totalCount"
          class="statistic-box"
        >
          <!-- 商品总价 -->
          <div class="item">
            <div class="tit">
              <span class="number">{{ orderInfo.totalCount }}</span>{{ $t('submitOrder.totalItems') }}：
            </div>
            <div class="con">
              ￥{{ parsePrice(orderInfo.total)[0] }}.{{
                parsePrice(orderInfo.total)[1]
              }}
            </div>
          </div>
          <!-- 商品运费 -->
          <div
            v-if="orderInfo.mold !== 1"
            class="item"
          >
            <div class="tit">
              {{ $t('orderDetails.productShipping') }}：
            </div>
            <div class="con">
              <p>
                ￥{{ parsePrice(transfee)[0] }}.{{
                  parsePrice(transfee)[1]
                }}
              </p>
            </div>
          </div>
          <!-- 商家条件包邮（运费减免） -->
          <div
            v-if="orderInfo.mold !== 1 && shopFreeTransFee"
            class="item"
          >
            <div class="tit">
              {{ $t('orderDetails.shippingDiscount') }}：
            </div>
            <div class="con bright">
              <p>
                -￥{{ parsePrice(shopFreeTransFee)[0] }}.{{
                  parsePrice(shopFreeTransFee)[1]
                }}
              </p>
            </div>
          </div>
          <!-- 平台开启会员包邮(运费减免) -->
          <div
            v-if="orderInfo.freeTransFee"
            class="item"
          >
            <div class="tit">
              {{ $t('submitOrder.memberPackage') }}：
            </div>
            <div class="con bright">
              <p>
                -￥{{ parsePrice(orderInfo.freeTransFee)[0] }}.{{
                  parsePrice(orderInfo.freeTransFee)[1]
                }}
              </p>
            </div>
          </div>
          <!-- 积分抵扣 -->
          <div
            v-if="isScorePay === 1"
            class="item"
          >
            <div class="tit red-font">
              {{ $t('submitOrder.pointsCredit') }}：
            </div>
            <div class="con bright">
              -￥{{ parsePrice(orderInfo.totalScoreAmount)[0] }}.{{
                parsePrice(orderInfo.totalScoreAmount)[1]
              }}
            </div>
          </div>
          <!-- 平台优惠券 -->
          <div
            v-if="platformCoupons && platformCoupons.couponAmount"
            class="item"
          >
            <div class="tit red-font">
              {{ $t('submitOrder.platformCoupons') }}：
            </div>
            <div class="con bright">
              -￥{{ parsePrice(platformCoupons.couponAmount)[0] }}.{{
                parsePrice(platformCoupons.couponAmount)[1]
              }}
            </div>
          </div>
          <!-- 会员折扣 -->
          <div
            v-if="orderInfo.totalLevelAmount"
            class="item"
          >
            <div class="tit">
              {{ $t('submitOrder.memberDiscount') }}：
            </div>
            <div class="con bright">
              -￥{{ parsePrice(orderInfo.totalLevelAmount)[0] }}.{{
                parsePrice(orderInfo.totalLevelAmount)[1]
              }}
            </div>
          </div>
          <!-- 店铺折扣 -->
          <div
            v-if="orderInfo.shopMemberAmount"
            class="item"
          >
            <div class="tit ">
              {{ $t('submitOrder.shopDiscount') }}：
            </div>
            <div class="con bright">
              -￥{{ parsePrice(orderInfo.shopMemberAmount)[0] }}.{{
                parsePrice(orderInfo.shopMemberAmount)[1]
              }}
            </div>
          </div>
          <!-- 店铺优惠 -->
          <div
            v-if="orderInfo.orderShopReduce"
            class="item"
          >
            <div class="tit red-font">
              {{ $t('submitOrder.storeDiscount') }}：
            </div>
            <div class="con bright">
              -￥{{ parsePrice(orderInfo.orderShopReduce)[0] }}.{{
                parsePrice(orderInfo.orderShopReduce)[1]
              }}
            </div>
          </div>
        </div>
        <!-- 应付总额 -->
        <div class="detail-box">
          <div class="item">
            <div class="tit">
              {{ $t('submitOrder.totalPayable') }}：
            </div>
            <div class="con">
              ￥{{ parsePrice(orderInfo.actualTotal)[0] }}.{{
                parsePrice(orderInfo.actualTotal)[1]
              }}
              <span v-if="totalScoreAmount">+ {{ totalScoreAmount }} {{ $t('prodDetail.points') }}</span>
            </div>
          </div>
          <div
            v-if="currentAddr.addrId && mold !== 1"
            class="item"
          >
            <span class="text">
              {{ $t('submitOrder.sendTo') }}：{{
                currentAddr.province +
                  ' ' +
                  currentAddr.city +
                  ' ' +
                  currentAddr.area +
                  ' ' +
                  currentAddr.addr
              }}
            </span>
            <span class="text">{{ $t('submitOrder.consignee') }}：{{ currentAddr.receiver }} {{ currentAddr.mobile }}</span>
          </div>
        </div>
        <div class="btn-box">
          <a
            v-if="shopCartOrders&&shopCartOrders.length>0"
            href="javascript:void(0)"
            class="btn"
            @click="submitOrder"
          >{{ $t('submitOrder.submitOrder') }}</a>
          <!-- 不支持配送 -->
          <a
            v-else
            href="javascript:void(0)"
            class="disable-btn"
          >{{ $t('submitOrder.submitOrder') }}</a>
        </div>
      </div>
      <!-- 金额明细 end -->
    </div>
    <!-- 地址弹窗 -->
    <add-or-edit-address
      v-if="showAddrPop"
      :edit-addr-id="editAddrId"
      @get-addr-list="getAddrList"
      @reload-order-info="loadOrderInfo"
      @toggle-addr-pop="toggleAddrPop"
    />
    <!-- /地址弹窗 -->
    <!-- 发票弹窗 -->
    <add-or-edit-invoice
      v-if="showInvoiceAdd"
      ref="invoiceAddOrUpdateRef"
      @toggle-addr-pop="refreshChange"
      @get-invoice-data="getInvoiceData"
      @hide-pop="hideInvoicePop"
    />
    <confirm-popup
      v-if="dialogVisible"
      :pop-configuration="deliveryConfig"
      @cancel="dialogVisible = false"
      @confirm="$router.go('-1')"
    />
  </div>
</template>

<script setup>
import Cookie from 'vue-cookies'
import { bus } from '@/utils/bus'
import * as util from '@/utils'
import { ElMessage } from 'element-plus'
import Big from 'big.js'

const formatDate = (val) => {
  if (val) {
    return util.tsToDate(val.replace(/-/g, '/'), 'Y-M-D')
  }
}
const showInvoiceAdd = ref(false) // 发票弹窗
// 商品运费
const transfee = ref(0)
// 减免运费
const shopFreeTransFee = ref(0)
const maxUsableScore = ref(0)
const userUseScore = ref('') // 使用多少积分抵扣
watch(maxUsableScore, (nv) => {
  if (userUseScore.value > nv) {
    userUseScore.value = nv
  }
})
let orderEntry = 0 // 订单入口 0购物车 1立即购买
let uuid = ''
const accountCanUseScore = ref(0) // 账号可用积分
const route = useRoute()
onMounted(() => {
  document.title = $t('submitOrder.submitOrder')
  // 获取当前账号可用积分
  http.get('/p/score/scoreLevel/page?levelType=' + 0).then(({ data }) => {
    accountCanUseScore.value = data.score
  })
  if (route.query.orderEntry) {
    orderEntry = route.query.orderEntry
  }
  uuid = genUUID()
  getAddrList()
  loadOrderInfo(true)
})
const languageStore = useLanguageStore()

onBeforeMount(() => {
  languageStore.handleChangeErrMsg('')
})
const invoiceAddOrUpdateRef = ref(null)
const showAddOrUpdateDialog = (st, shopCart, shopId) => {
  showInvoiceAdd.value = true
  const param = shopCart.invoiceDataFrom ? shopCart.invoiceDataFrom : ''
  nextTick(() => {
    invoiceAddOrUpdateRef.value?.init(st, param, '', shopId)
  })
}
/**
 * 刷新回调
 */
const refreshChange = (visible) => {
  showInvoiceAdd.value = visible
}
/**
 * 发票信息
 */
const shopCartOrders = ref([])
const getInvoiceData = (invoiceDataFrom) => {
  if (invoiceDataFrom.headerType === 2) {
    delete invoiceDataFrom.invoiceTaxNumber
  }
  shopCartOrders.value.forEach((item) => {
    if (item.shopId === invoiceDataFrom.shopId) {
      item.invoiceDataFrom = invoiceDataFrom
    }
  })
  showInvoiceAdd.value = false
}
const hideInvoicePop = (visible) => {
  showInvoiceAdd.value = visible
}
/**
 * 积分输入
 */
const shopUseScore = ref('') // 积分抵扣比例
const inputComplete = util._debounce(() => {
  let isUserUseScore = userUseScore.value.toString().replace(/[^\d]/g, '') // 清除“数字”和“.”以外的字符
  if (isUserUseScore.indexOf('.') < 0 && isUserUseScore !== '') {
    // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
    isUserUseScore = parseInt(isUserUseScore)
  }
  userUseScore.value = isUserUseScore
  if (shopUseScore.value > 100) {
    userUseScore.value = userUseScore.value - userUseScore.value % 10
  }
  if (userUseScore.value > maxUsableScore.value) {
    userUseScore.value = maxUsableScore.value
  }
  loadOrderInfo()
}, 500)

/**
 * 获取地址列表
 */
const addressList = ref([])
const getAddrList = () => {
  http.get('/p/address/list').then(({ data }) => {
    addressList.value = data
  })
}

/**
 * 选择地址
 */
const currentAddr = ref({}) // 当前选择的地址
const selectedAddrId = ref(0)
const changeAddress = (addrId) => {
  addressList.value.forEach(element => {
    if (element.addrId === addrId) {
      currentAddr.value = element
    }
  })
  selectedAddrId.value = addrId
  loadOrderInfo()
}

/**
 * 改变优惠券选择
 */
const platformCoupons = ref({
  canUseCoupons: [],
  unCanUseCoupons: []
})
let userChangeCoupon = 0 // 用户有没有对优惠券进行改变
let couponIds = []
let couponUserIds = []
const checkCoupon = () => {
  const isCouponIds = []
  const isCouponUserIds = []
  shopCartOrders.value.forEach(shopCart => {
    if (shopCart.shopCoupons) {
      shopCart.shopCoupons.canUseCoupons.forEach(coupon => {
        if (coupon.choose) {
          isCouponIds.push(coupon.couponId) // couponUserId
          isCouponUserIds.push(coupon.couponUserId)
        }
      })
    }
  })
  if (platformCoupons.value && platformCoupons.value.canUseCoupons.length) {
    platformCoupons.value.canUseCoupons.forEach(coupon => {
      if (coupon.choose) {
        isCouponIds.push(coupon.couponId)
        isCouponUserIds.push(coupon.couponUserId)
      }
    })
  }
  couponIds = isCouponIds
  couponUserIds = isCouponUserIds
  userChangeCoupon = 1
  loadOrderInfo()
}

/**
 * 设置为默认地址
 */
const setDefaultAddr = (addrId) => {
  http.put('/p/address/defaultAddr/' + addrId).then(({ data }) => {
    ElMessage({
      message: data,
      type: 'success',
      duration: 1000
    })
    getAddrList()
  })
}
/**
 * 显示/隐藏确认删除弹窗
 */
const showDelAddr = ref(false)
const editAddrId = ref(0) // 要修改的地址id
const toggleDelAddr = (sts, addrId) => {
  showDelAddr.value = sts
  editAddrId.value = addrId
}
/**
 * 显示/隐藏地址弹窗
 */
const showAddrPop = ref(false) // 地址弹窗显隐
const toggleAddrPop = (sts) => {
  if (Cookie.get('bbcToken')) {
    showAddrPop.value = sts
    editAddrId.value = 0
  } else {
    bus.emit('showLogin', true)
    showAddrPop.value = false
  }
}

/**
 * 修改地址 (弹窗传地址id)
 */
const editAddr = (addrId) => {
  if (Cookie.get('bbcToken')) {
    showAddrPop.value = true
    editAddrId.value = addrId
  } else {
    bus.emit('showLogin', true)
    showAddrPop.value = false
  }
}
/**
 * 删除地址
 */
const delAddr = () => {
  let reload = false
  if (selectedAddrId.value === editAddrId.value) {
    selectedAddrId.value = 0
    reload = true
  }
  http
    .delete('/p/address/deleteAddr/' + editAddrId.value)
    .then(({ data }) => {
      ElMessage({
        message: data,
        type: 'success',
        duration: 1000
      })
      toggleDelAddr(false)
      getAddrList()
      if (reload) {
        loadOrderInfo()
      }
    })
}
/**
 * 价格处理
 */
const parsePrice = (value) => {
  let val = Number(value)
  if (!val) {
    val = 0
  }
  // 截取小数点后两位，并以小数点为切割点将val转化为数组
  return val.toFixed(2).split('.')
}

/**
 * 积分抵现选择
 */
const checked = ref(false) // 积分抵现选框
const isScorePay = ref(0) // 用户是否选择积分抵现(0不使用 1使用 默认不使用)
const orderInfo = ref({})
const isProhibit = ref(false) // （积分抵现）checkbox是否禁止
const useMemberPoints = () => {
  userUseScore.value = ''
  if (orderInfo.value.maxUsableScore > 0) {
    // maxUsableScore 整个订单可以使用的积分数
    isProhibit.value = false // （积分抵现）checkbox是否禁止
    // 如果积分可抵扣
    if (checked.value) {
      isScorePay.value = 1 // 用户是否选择积分抵现(0不使用 1使用 默认不使用)
    } else if (!checked.value) {
      isScorePay.value = 0 // 用户是否选择积分抵现(0不使用 1使用 默认不使用)
    }
    setTimeout(() => {
      loadOrderInfo() // 加载订单数据
    }, 800)
  } else if (orderInfo.value.maxUsableScore <= 0) {
    isProhibit.value = true // （积分抵现）checkbox是否禁止
  }
}

/**
 * 加载订单数据
 */
const filterShopItems = ref([]) // 不支持配送的商品
const totalScoreAmount = ref(0) // 积分抵扣金额
const mold = ref(0) // 商品类型（1虚拟商品）
const router = useRouter()
const loadOrderInfo = (isFirst) => {
  const orderParam = {
    addrId: selectedAddrId.value,
    orderItem:
      orderEntry === '1' ? JSON.parse(sessionStorage.getItem('bbcOrderItem')) : undefined,
    basketIds:
      orderEntry === '0' ? JSON.parse(sessionStorage.getItem('bbcBasketIds')) : undefined,
    couponIds,
    couponUserIds,
    isScorePay: isScorePay.value,
    userChangeCoupon,
    userUseScore: Number(userUseScore.value),
    dvyType: 1,
    uuid
  }
  http.post('/p/order/confirm', orderParam).then(({ data }) => {
    // 不支持地区商品数据处理
    if (data.filterShopItems && data.filterShopItems.length > 0) {
      const isFilterShopItems = []

      data.filterShopItems.forEach(el => {
        el.isDelivery = false

        // 如果店铺有支持配送的商品则一起显示
        const shopCartFlg = data.shopCartOrders?.some(shopCart => {
          if (el.shopId === shopCart.shopId) {
            shopCart.shopCartItemDiscounts[0].shopCartItems.push(el)
            return true
          } else {
            return false
          }
        })
        // 没有支持配送的商品独立显示
        if (!shopCartFlg) {
          const filterFlg = isFilterShopItems?.some(filterShop => {
            if (filterShop.shopId === el.shopId) {
              filterShop.shopCartItems.push(el)
              return true
            } else {
              return false
            }
          })

          if (!filterFlg) {
            isFilterShopItems.push({
              shopId: el.shopId,
              shopName: el.shopName,
              shopCartItems: [el]
            })
          }
        }
      })

      filterShopItems.value = isFilterShopItems
    } else {
      filterShopItems.value = []
    }
    const remarksList = []
    if (!isFirst) {
      shopCartOrders.value.forEach(el => {
        remarksList.push(el.remarks)
        // 获取上次输入的虚拟商品留言
        data.shopCartOrders.forEach(item => {
          if (el.shopId === item.shopId) {
            el.shopCartItemDiscounts.forEach(el1 => {
              el1.shopCartItems.forEach(el2 => {
                item.shopCartItemDiscounts.forEach(item1 => {
                  item1.shopCartItems.forEach(item2 => {
                    if (el2.prodId === item2.prodId) {
                      item2.virtualRemarkList = el2.virtualRemarkList
                    }
                  })
                })
              })
            })
          }
        })
      })
    }
    const isCouponIds = []
    totalScoreAmount.value = data.orderType === 'SCORE' ? shopCartOrders.value[0].shopCartItemDiscounts[0].shopCartItems[0].scorePrice : data.scorePrice
    orderInfo.value = data
    maxUsableScore.value = data.maxUsableScore // 订单最大可用积分数量
    if (data.userAddr) {
      currentAddr.value = data.userAddr
      selectedAddrId.value = data.userAddr.addrId
    }
    platformCoupons.value = splitCouponAndPushCouponIds(
      data.coupons,
      isCouponIds
    ) // 平台优惠券
    const isShopCartOrders = data.shopCartOrders
    isShopCartOrders.forEach((shopCart, index) => {
      if (isFirst) {
        shopCart.remarks = ''
      } else {
        shopCart.remarks = remarksList[index]
      }
      shopCart.shopCoupons = splitCouponAndPushCouponIds(
        shopCart.coupons,
        isCouponIds
      )
    })
    shopCartOrders.value = isShopCartOrders
    couponIds = isCouponIds
    shopUseScore.value = data.shopUseScore // 积分抵扣比例
    transfee.value = new Big(data.shopFreeTransFee || 0).plus(Math.abs(data.totalTransFee) || 0).valueOf()
    shopFreeTransFee.value = data.shopFreeTransFee
    // 商品类型（4虚拟商品）
    mold.value = data.mold || 0
    handleAllVirtualMsg()
  }).catch(() => {
    router.push({ path: '/cart' })
  })
}
/**
 * 分割优惠券成
 * 1. canUseCoupons 可使用优惠券列表
 * 2. unCanUseCoupons 不可使用优惠券列表
 * 3. couponAmount 选中的优惠券可优惠金额
 * 4. 将选中的优惠券ids保存起来
 * @param {*} coupons 优惠券列表
 * @param {*} couponIds 选中的优惠券id
 */
const splitCouponAndPushCouponIds = (coupons, couponIds) => {
  if (!coupons || !coupons.length) {
    return
  }
  const canUseCoupons = []
  const unCanUseCoupons = []
  let couponAmount = 0
  coupons.forEach(coupon => {
    if (coupon.canUse) {
      canUseCoupons.push(coupon)
    } else {
      unCanUseCoupons.push(coupon)
    }
    if (coupon.choose) {
      couponIds.push(coupon.couponId)
      couponAmount = coupon.reduceAmount
    }
  })
  return {
    canUseLength: canUseCoupons.length,
    couponAmount,
    canUseCoupons,
    unCanUseCoupons
  }
}

/**
 * 虚拟商品留言
 */
let allVirtualMsg = [] // 全部留言列表
const handleAllVirtualMsg = () => {
  allVirtualMsg = getValueOfArr(shopCartOrders.value)
}
const getValueOfArr = (data) => {
  const layers = ['shopCartItemDiscounts', 'shopCartItems', 'virtualRemarkList']
  const deepGet = (item, index) => {
    return item.map(la => {
      const children = la[layers[index]]
      if (Array.isArray(children)) {
        if (layers.length === index + 1) {
          return children.map((ch, idx) => {
            ch.id = la.prodId + '_' + idx
            return ch
          })
        }
        return deepGet(children, index + 1)
      }
      return []
    }).flat(Infinity)
  }
  return deepGet(data, 0)
}

/**
 * 虚拟商品留言输入框失焦
 */
const handleInputBlur = (value, msgIndex, prodIndex, discIndex, shopIndex) => {
  if (!value) {
    return
  }
  if (!value.trim()) {
    shopCartOrders.value[shopIndex].shopCartItemDiscounts[discIndex].shopCartItems[prodIndex].virtualRemarkList[msgIndex].value = value.trim()
    // virtualRemarkList[msgIndex].value = value.trim()
    return
  }
  const currentItem = shopCartOrders.value[shopIndex].shopCartItemDiscounts[discIndex].shopCartItems[prodIndex].virtualRemarkList[msgIndex]
  allVirtualMsg.forEach(msgItem => {
    if (currentItem.id === msgItem.id) {
      msgItem.value = value
    }
  })
}

/**
 * 提交订单
 */
const dialogVisible = ref(false)
const deliveryConfig = ref({
  title: '提示',
  firstLineText: '',
  confirmText: '确认',
  cancelText: '取消'
})
const submitOrder = () => {
  const orderShopParam = []
  const reg = /^\s+$/g
  shopCartOrders.value.forEach(shopCart => {
    orderShopParam.push({
      remarks: shopCart.remarks,
      shopId: shopCart.shopId
    })
  })
  const remarksFlag = orderShopParam.some(item => {
    return reg.test(item.remarks)
  })

  if (remarksFlag) {
    ElMessage({
      message: $t('inputAllSpace'),
      type: 'error',
      duration: 1000
    })
    return
  }
  let orderInvoiceList = [] // invoiceDataFrom
  shopCartOrders.value.forEach((item) => {
    if (item.invoiceDataFrom && item.invoiceDataFrom.invoiceType === 1 && item.actualTotal) {
      orderInvoiceList.push(item.invoiceDataFrom)
    }
  })
  if (orderInvoiceList.length === 0) {
    orderInvoiceList = null
  }
  if (mold.value !== 1 && !addressList.value.length) {
    if (Cookie.get('bbcToken')) {
      ElMessage({
        message: $t('submitOrder.pleaseAddTheAddressFirst'),
        type: 'warning',
        duration: 1000
      })
      showAddrPop.value = true
    } else {
      bus.emit('showLogin', true)
      showAddrPop.value = false
    }
    return
  }

  if (mold.value !== 1 && selectedAddrId.value === 0) {
    ElMessage({
      message: $t('submitOrder.pleaseSelectTheAddressFirst'),
      type: 'warning',
      duration: 1000
    })
    document.body.scrollTop = document.documentElement.scrollTop = 0
    return
  }
  if (checked.value && !userUseScore.value) {
    ElMessage({
      message: $t('submitOrder.pleaseEnterTheNumberOfPoints'),
      type: 'warning',
      duration: 1000
    })
    return
  }

  if (allVirtualMsg.length && allVirtualMsg.find(el => el.isRequired && !el.value)) {
    ElMessage({
      message: $t('submitOrder.messageCannotBeEmpty'),
      type: 'warning',
      duration: 2000
    })
    return
  }
  allVirtualMsg.forEach(el => {
    el.id = undefined
  })
  const orderFlowLogParam = JSON.parse(localStorage.getItem('bbcFlowAnalysisLogDto')) || {}
  let step = localStorage.getItem('bbcStep') * 1
  step += 1
  orderFlowLogParam.visitType = 1
  orderFlowLogParam.step = step
  http
    .post('/p/order/submit', {
      orderShopParams: orderShopParam,
      uuid,
      orderInvoiceList,
      virtualRemarkList: allVirtualMsg,
      orderFlowLogParam
    })
    .then(({ data }) => {
      // 请求成功后，更新缓存
      localStorage.setItem('bbcStep', step)
      localStorage.setItem('bbcFlowAnalysisLogDto', JSON.stringify(orderFlowLogParam))
      localStorage.setItem('bbcSessionTimeStamp', new Date().getTime()) // 更新会话时间

      if (data.duplicateError === 1) {
        languageStore.handleChangeErrMsg($t('submitOrder.duplicateErrorTips'))
        return ElMessage.warning($t('submitOrder.duplicateErrorTips'))
      }
      sessionStorage.setItem('bbcPay_total', orderInfo.value.actualTotal)
      sessionStorage.setItem('bbcPay_orderNumber', data.orderNumbers)
      sessionStorage.setItem('bbcPay_mold', mold.value)
      router.push({
        path: '/payment'
      })
      getCartCount()
    })
    .catch(({ data }) => {
      if (data.code === 'A07001') {
        shopCartOrders.value.forEach((shopCart) => {
          shopCart.shopCartItemDiscounts.forEach((shopCartItemDiscount) => {
            shopCartItemDiscount.shopCartItems.forEach((prodItem) => {
              if (!prodItem.isDelivery) {
                data.msg += prodItem.prodName + '、'
              }
            })
          })
        })
        data.msg = data.msg.substring(0, data.msg.length - 1)
        deliveryConfig.value.firstLineText = data.msg
        dialogVisible.value = true
      }
    })
}

/**
 * 获取购物车商品总数
 */
const cartNumberStore = useCartNumberStore()

const getCartCount = () => {
  http.get('/p/shopCart/prodCount').then(({ data }) => {
    cartNumberStore.changeCartNumber(data)
  })
}

/**
 * 生成uuid
 */
const genUUID = () => {
  const s = []
  const hexDigits = '0123456789abcdef'
  for (let i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = '-'

  return s.join('')
}

</script>

<style scoped lang="scss">
@use './index.scss';
</style>
